package fonkin.com.wifisignapp.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.liaoinstan.springview.widget.SpringView;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import fonkin.com.wifisignapp.R;
import fonkin.com.wifisignapp.acticity.LoginActivity;
import fonkin.com.wifisignapp.acticity.addressList.SearchUser;
import fonkin.com.wifisignapp.acticity.news.NewsDetail;
import fonkin.com.wifisignapp.adapter.news.NewsAdapter;
import fonkin.com.wifisignapp.bean.app.BannerInfor;
import fonkin.com.wifisignapp.bean.news.NewsInfor;
import fonkin.com.wifisignapp.bean.news.NewsType;
import fonkin.com.wifisignapp.retrofit.BaseRetrofit;
import fonkin.com.wifisignapp.constants.AppConstants;
import fonkin.com.wifisignapp.retrofit.GlideImageLoader;
import fonkin.com.wifisignapp.retrofit.ServiceApis;
import fonkin.com.wifisignapp.utils.PrintLog;
import fonkin.com.wifisignapp.utils.ReturnVo;
import fonkin.com.wifisignapp.utils.ShowToast;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 黄洪靖 on 2018/4/11.
 */
public class HomeFragment extends Fragment implements View.OnKeyListener{
    Banner banner = null;
    TextView textView;
    ImageView imageView;
    ImageView bgImage;
    ListView news_list_infor;
    LinearLayout x_lineraLayout,y_lineraLayout,t_notice;
    private long exitTime = 0;
    List<NewsInfor> newsInforList = null;
    List<String> imageArray = new ArrayList<>();
    List<String> imageTitle = new ArrayList<>();
    public static HomeFragment newInstance(String text){
        HomeFragment  homeFragment =new HomeFragment();
        Bundle bundle=new Bundle();
        bundle.putString("text",text);
        homeFragment.setArguments(bundle);
        return homeFragment;
    }

    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.home_fragment,container,false);
        textView= (TextView) view.findViewById(R.id.textView);
        textView.setText(getArguments().getString("text"));

        return view;

    }

    private void initView() {
        initRetrofit("校内新闻");
        imageView = (ImageView)getView().findViewById(R.id.type_no_news);
        //校内新闻
        x_lineraLayout= (LinearLayout) getView().findViewById(R.id.x_news);
        x_lineraLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageView.setVisibility(View.GONE);
                String typeName = "校内新闻";
                initRetrofit(typeName);
            }


        });

        //院内新闻
        y_lineraLayout= (LinearLayout) getView().findViewById(R.id.y_news);
        y_lineraLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageView.setVisibility(View.GONE);
                String typeName = "院内新闻";
                initRetrofit(typeName);
            }


        });

        //通知公告
        t_notice= (LinearLayout) getView().findViewById(R.id.t_notice);
        t_notice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageView.setVisibility(View.GONE);
                String typeName = "通知公告";
                initRetrofit(typeName);
            }


        });

    }


    public void initRetrofit(String typeName){
        news_list_infor  = (ListView)getView().findViewById(R.id.home_goods_listView);
        final NewsAdapter newAdapter = new NewsAdapter(getActivity(),new ArrayList<NewsInfor>());
        news_list_infor.setAdapter(newAdapter);
        final Call<ReturnVo<List<NewsInfor>>> newsList = BaseRetrofit.GetBaseRetrofit().getNewsList(typeName);
        newsList.enqueue(new Callback<ReturnVo<List<NewsInfor>>>() {
            @Override
            public void onResponse(Call<ReturnVo<List<NewsInfor>>> call, Response<ReturnVo<List<NewsInfor>>> response) {
                PrintLog.printApi(response,call);
                if (response.isSuccessful()){
                    if (response.body().getCode().equals(1)){
                        newsInforList = response.body().getData();
                        if (!newsInforList.isEmpty()) {
                            newAdapter.addAll(newsInforList);
                            setListViewHeightBasedOnChildren(news_list_infor);
                            news_list_infor.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    NewsInfor newsInfor = newsInforList.get(position);
                                    Intent intent = new Intent(getActivity(), NewsDetail.class);
                                    intent.putExtra("flg", "1");
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable("newsInfor", (Serializable) newsInfor);
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                }
                            });
                        }else {
                            bgImage.setVisibility(View.VISIBLE);
                            Picasso
                                    .with(getContext())
                                    .load(R.drawable.none_data)
                                    .resize(500,400)
                                    .into(bgImage);
                        }
                    }
                }else {

                }
                newAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(Call<ReturnVo<List<NewsInfor>>> call, Throwable t) {
                ShowToast.ShowToastShort("XXXX",getActivity());
            }
        });
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        initView();
        super.onActivityCreated(savedInstanceState);
        banner = (Banner) getView().findViewById(R.id.banner);
        Call<ReturnVo<List<BannerInfor>>> bannerList = BaseRetrofit.GetBaseRetrofit().getBanner();
        bannerList.enqueue(new Callback<ReturnVo<List<BannerInfor>>>() {
            @Override
            public void onResponse(Call<ReturnVo<List<BannerInfor>>> call, Response<ReturnVo<List<BannerInfor>>> response) {
                if (response.isSuccessful()){
                    if (response.body().getCode().equals(AppConstants.SUCCESS)){
                        List<BannerInfor> data = response.body().getData();
                        if (!data.isEmpty()){
                            for (BannerInfor banner:data) {
                                imageArray.add(AppConstants.IMAGE_API+banner.getBannerImage().trim());
                                imageTitle.add(banner.getTitle().trim());
                            }
                        }else{
                            //设置图片集合
                            imageArray = new ArrayList<>();
                            imageArray.add("http://img.zcool.cn/community/01c8dc56e1428e6ac72531cbaa5f2c.jpg");
                            imageArray.add("http://img.zcool.cn/community/0114a856640b6d32f87545731c076a.jpg");
                            imageArray.add("http://img.zcool.cn/community/01fda356640b706ac725b2c8b99b08.jpg");
                            //设置图片标题集合
                            imageTitle = new ArrayList<>();
                            imageTitle.add("aaaaaaaaa");
                            imageTitle.add("bbbbbbbbb");
                            imageTitle.add("ccccccccc");
                        }

                        //设置banner样式
                        banner.setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE);
                        //设置图片加载器
                        banner.setImageLoader(new GlideImageLoader());
                        //设置图片集合
                        banner.setImages(imageArray);
                        //设置banner动画效果
                        banner.setBannerAnimation(Transformer.ZoomOutSlide);
                        //设置标题集合（当banner样式有显示title时）
                        banner.setBannerTitles(imageTitle);
                        //设置自动轮播，默认为true
                        banner.isAutoPlay(true);
                        //设置轮播时间
                        banner.setDelayTime(3500);
                        //设置指示器位置（当banner模式中有指示器时）
                        banner.setIndicatorGravity(BannerConfig.CENTER);
                        //banner设置方法全部调用完毕时最后调用
                        banner.start();
                    }
                }
            }

            @Override
            public void onFailure(Call<ReturnVo<List<BannerInfor>>> call, Throwable t) {
                ShowToast.ShowToastShort("XXXXX",getActivity());
            }
        });

    }


    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            // ToDo
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getActivity(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                // 这里是我做了保存数据操作
                getActivity().finish();
                System.exit(0);
            }
            return true;
        }
        return false;
    }
}
